package cn.com.io.day20151215;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;

/**
 * 文件复制功能
 */
public class FileChannelTest {
    public static void main(String[] args) throws IOException {
        FileChannel inChannel = null;
        FileChannel outChannel = null;
        try {
            File f = new File("./src/cn/com/io/day20151215/FileChannelTest.java");
            inChannel = new FileInputStream(f).getChannel();//创建FileInputStream，以该文件输入流创建FileChannel
            MappedByteBuffer buffer = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, f.length());//将FileChannel里的数据映射成ByteBuffer
            Charset charset = Charset.forName("UTF-8");//使用UTF-8的字符集来创建解码器
            outChannel = new FileOutputStream("fileChannelTest.txt").getChannel();//以文件输出流创建FileChannel,用以控制输出
            outChannel.write(buffer);//直接将buffer里的数据全部输出
            buffer.clear();//复原limit、position的位置
            CharsetDecoder decoder = charset.newDecoder();//创建解码器（CharsetDecoder）对象
            CharBuffer charBuffer = decoder.decode(buffer);//使用解码器将byteBuffer转换成charBuffer
            System.out.println(charBuffer);//CharBuffer里的toString方法可以获取对应的字符串
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(inChannel !=null){
                inChannel.close();
            }
            if(outChannel !=null){
                outChannel.close();
            }
        }
    }
}
